Python Lists


In [47]:
a = [1,2,3,4,5]

In [48]:
print a


[1, 2, 3, 4, 5]

In [49]:
# print a+1 # ERROR!!! TypeError: can only concatenate list (not "int") to list

a = a + [6] # or a.append(6)
print a


[1, 2, 3, 4, 5, 6]

In [50]:
while 3 in a:
    a.remove(3) # Inplace removal
print a


[1, 2, 4, 5, 6]

In [51]:
a.append(3) # Inplace append
print a


[1, 2, 4, 5, 6, 3]

In [21]:
print "Popped value from a:", a.pop() # pop() will remove the rightmost (most recent) element and return it
print "Now a = ",a


Popped value from a: 6
Now a =  [1, 2, 4, 5]

In [24]:
print "Pushing value 25 into a"
a.append(25)             # .append() is the same as a push() operation
print "Now a = ",a


Pushing value 25 into a
Now a =  [1, 2, 4, 5, 25, 25]

In [26]:
a.count(25)


Out[26]:
2

In [31]:
def dedup_list(a_list):
    out_list = []
    for i in a_list:
        if i not in out_list:
            out_list.append(i)
    return out_list

print dedup_list(a)


[1, 2, 4, 5, 25]

In [30]:
deduped = list(set(a))
print deduped


[1, 2, 4, 5, 25]

Slicing and Copying


In [45]:
a = [1,2,3,4,5]
# Slices are defined by list_to_slice[start_index:end_index:step]
# slice is given from start_index(included) till end_index(excluded)

print "Original list a:\t%s" % a
print "Complete slice of a:\t%s" % a[:]
print "First 3 elements in a:\t%s" % a[:3]
print "First 4 elements alternate:\t%s" % a[:3:2]
print "Reverse list :\t%s" % a[-1::-1]


Original list a:	[1, 2, 3, 4, 5]
Complete slice of a:	[1, 2, 3, 4, 5]
First 3 elements in a:	[1, 2, 3]
First 4 elements alternate:	[1, 3]
Reverse list :	[5, 4, 3, 2, 1]

In [ ]:

Map, Filter and Reduce


In [33]:
temp_celsius = [0,10,20,30,40,50,60,70,80,90,100]

In [36]:
# Map example
# Convert the celsius values to fahrenheit
temp_fahr = map(lambda x: 1.8*x + 32, temp_celsius)
print temp_fahr


[32.0, 50.0, 68.0, 86.0, 104.0, 122.0, 140.0, 158.0, 176.0, 194.0, 212.0]

In [37]:
# Filter example
# show only fahrenheit values divisible by 4
print filter(lambda x: x%4==0, temp_fahr)


[32.0, 68.0, 104.0, 140.0, 176.0, 212.0]

In [40]:
# Reduce
# Accumulate product of all numbers
a = range(1,10)
print a
print reduce(lambda x,y: x*y, a)


[1, 2, 3, 4, 5, 6, 7, 8, 9]
362880
-43

In [ ]: